//
//  SEGSettingPasswordViewController.m
//  SEGUhomeStandard
//
//  Created by 乔杨 on 2019/4/10.
//  Copyright © 2019 刘山. All rights reserved.
//

#import "SEGSettingPasswordViewController.h"
#import <Commom/UITextField+Limit.h>
#import <Commom/SEGSafaKeyboard.h>
#import <Commom/SEGPasswordTextField.h>

#import "SEGSettingPasswordViewModel.h"

@interface SEGSettingPasswordViewController ()<UITextFieldDelegate>

/** 大标题 */
@property (nonatomic, strong) SEGBigNavigationView *bigNavView;
/** 描述Lab */
@property (nonatomic, strong) UILabel *desLab;
/** line */
@property (nonatomic, strong) UIView *line;
/** 密码 */
@property (nonatomic, strong) SEGPasswordTextField *pwdTF;
/** 密码可看 */
@property (nonatomic, strong) UIButton *seePasswordButton;
/** 进入 */
@property (nonatomic, strong) UIButton *nextBtn;

/// viewModel
@property (nonatomic, strong) SEGSettingPasswordViewModel *viewModel;

@end

@implementation SEGSettingPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_W;
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    [self.bigNavView setTitleWithString:@"设置密码"];
    
    [self createUI];
    // 请求密码配置
    [self requestPasswordConfig];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.pwdTF becomeFirstResponder];
    });
    
    
    //注册通知 监听用户截屏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleUserDidTakeScreenshot:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    if (@available(iOS 11.0, *)) {
        // 监测当前设备是否处于录屏状态
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
        
        // 监听用户是否录屏
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleScreenCapturedDidChange:) name:UIScreenCapturedDidChangeNotification object:nil];
    }
}

#pragma mark - Load Data
// 请求密码配置
- (void)requestPasswordConfig {
    [self.viewModel.reqConfigSignal subscribeNext:^(id result) {
        if ([result isKindOfClass:[NSString class]]) {
            self.desLab.text = result;
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineSpacing = 8 - (self.desLab.font.lineHeight - self.desLab.font.pointSize);
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
            self.desLab.attributedText = [[NSAttributedString alloc] initWithString:result attributes:attributes];
        }
    }];
}
// 校验密码格式是否正确
- (void)requestPasswordIsVaild {
    [self.viewModel.vaildCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    [[self.viewModel.vaildCommand execute:self.pwdTF.text] subscribeNext:^(id  _Nullable x) {
        // 选择社区VC
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:self.phoneStr forKey:@"tel"];
        [dic setObject:self.smsCode forKey:@"smsCode"];
        [dic setObject:self.randomToken forKey:@"randomToken"];
        [dic setObject:self.pwdTF.text forKey:@"password"];
        [dic setObject:@(YES) forKey:@"isFromLogin"];
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initSelectCommunityViewController:dic];
        [self.navigationController pushViewController:vc animated:YES];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason withtime:1.5];
    }];
}

#pragma mark - UI
- (void)createUI {
    [self.view addSubview:self.desLab];
    [self.desLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bigNavView.mas_bottom);
        make.left.equalTo(self.view).mas_offset(30);
        make.right.equalTo(self.view).mas_offset(-30);
    }];
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bigNavView.mas_bottom).mas_offset(110);
        make.left.equalTo(self.view).mas_equalTo(30);
        make.right.equalTo(self.view).mas_offset(-30);
        make.height.mas_equalTo(0.5);
    }];
    [self.view addSubview:self.pwdTF];
    [self.pwdTF mas_makeConstraints:^(MASConstraintMaker* make) {
        make.bottom.equalTo(self.line.mas_top);
        make.left.equalTo(self.line.mas_left);
        make.right.equalTo(self.line.mas_right).mas_offset(-30);
        make.height.mas_equalTo(17 + 34);
    }];
//    [self.view addSubview:self.seePasswordButton];
//    [self.seePasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(self.line.mas_top);
//        make.right.equalTo(self.line.mas_right);
//        make.width.mas_equalTo(30);
//        make.height.equalTo(self.pwdTF);
//    }];
    [self.view addSubview:self.nextBtn];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line.mas_bottom).mas_offset(120*kScaleWidth);
        make.right.equalTo(self.view.mas_right).mas_offset(-30);
        make.width.mas_equalTo(125);
        make.height.mas_equalTo(44);
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - Event
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
//- (void)segSeePassword:(UIButton *)button {
//    self.pwdTF.secureTextEntry = button.isSelected;
//    button.selected = !button.selected;
//}
- (void)nextButtonClick {
    // 调接口校验注册密码
    [self requestPasswordIsVaild];
}

#pragma mark - NSNotification
- (void)handleUserDidTakeScreenshot:(NSNotification *)notification {
    [SEGAlertView showTmepMessageWithMessage:KDetectScreenShotTipMessage withtime:2];
}
- (void)handleScreenCapturedDidChange:(NSNotification *)notification {
    NSLog(@"%s %@", __func__, notification);
    if (@available(iOS 11.0, *)) {
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
    }
}

#pragma mark - Getter
- (SEGBigNavigationView *)bigNavView {
    if (!_bigNavView) {
        _bigNavView = [[SEGBigNavigationView alloc] initWithType:SEGBigNavBar_backBtn];
        _bigNavView.frame = CGRectMake(0, 0, LYScreenWidth(), kBackBtn_BigNavHeight);
        _bigNavView.fontSize = 30;
        [self.view addSubview:_bigNavView];
    }
    return _bigNavView;
}
- (UILabel *)desLab {
    if (!_desLab) {
        _desLab = [[UILabel alloc] init];
        _desLab.textColor = kColor_3;
        _desLab.font = kFont_15;
        _desLab.numberOfLines = 0;
    }
    return _desLab;
}
- (UIView *)line {
    if (!_line) {
        _line = [[UIView alloc] init];
        _line.backgroundColor = kColor_L2;
    }
    return _line;
}
- (SEGPasswordTextField *)pwdTF {
    if (!_pwdTF) {
        _pwdTF = [[SEGPasswordTextField alloc] init];
        [_pwdTF setTextColor:kColor_1];
        [_pwdTF setTintColor:kColor_T];
        [_pwdTF setFont:kFont_17];
        [_pwdTF setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _pwdTF.secureTextEntry = YES;
        _pwdTF.delegate = self;
        [_pwdTF configPasswordInputLimitWithDelegate:self currentView:self.view];
        WeakSelf;
        _pwdTF.segTextDidChangeBlock = ^(NSString *text) {
            weakSelf.nextBtn.enabled = text.length >= 8;
        };
    }
    return _pwdTF;
}
- (UIButton *)seePasswordButton {
    if (!_seePasswordButton) {
        //发送验证码 按钮
        _seePasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_seePasswordButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_login_hide")]
                            forState:UIControlStateNormal];
        [_seePasswordButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_login_show")]
                            forState:UIControlStateSelected];
        //[_seePasswordButton addTarget:self action:@selector(segSeePassword:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _seePasswordButton;
}
- (UIButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [_nextBtn setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [_nextBtn setBackgroundImage:[UIImage imageWithColor:kColor_L2] forState:UIControlStateDisabled];
        [_nextBtn setTitle:@"选择社区" forState:UIControlStateNormal];
        _nextBtn.titleLabel.font = kFont_16;
        [_nextBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
        [_nextBtn setTitleColor:[UIColor seg_setColorWithAny:kColor_W dark:kColor_C] forState:UIControlStateDisabled];
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.layer.cornerRadius = 22;
        [_nextBtn addTarget:self
                     action:@selector(nextButtonClick)
           forControlEvents:UIControlEventTouchUpInside];
        _nextBtn.enabled = NO;
    }
    return _nextBtn;
}
- (SEGSettingPasswordViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGSettingPasswordViewModel new];
    return _viewModel;
}

@end
